<template>
  <div style="width: 100%">
    <div style="position: relative">
      <u-swiper keyName="img" height="550" :list="bannerList" @click="imgclick"></u-swiper>
      <div style="position: absolute; top: 60px; left: 5px; display: flex; font-weight: bolder; align-items: center; z-index: 10" @click="chooseLocation">
        <u-icon name="map" color="#fff" size="38"></u-icon>
        <span style="color: #fff; padding-left: 10px; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{ locationName }}</span>
        <u-icon name="arrow-down" color="#fff" size="24" style="margin-left: 5px"></u-icon>
      </div>
      <div style="position: absolute; top: 90px; left: 10px; width: 85%; display: flex">
        <input
          v-model="searchName"
          placeholder="智享洗衣9.9元洗衣"
          style="z-index: 0; border: none; border-radius: 23px; background: #fff; width: 100%; height: 35px; line-height: 35px; font-size: 14px; padding: 0 15px; box-sizing: border-box"
          @confirm="handleSearch"
        />
        <div
          v-if="searchName"
          @click="clearSearch"
          style="
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
            background: #ccc;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
          "
        >
          <div style="width: 10px; height: 2px; background: #fff; transform: rotate(45deg); position: absolute"></div>
          <div style="width: 10px; height: 2px; background: #fff; transform: rotate(-45deg); position: absolute"></div>
        </div>
      </div>
    </div>
    <div style="padding: 0 15px">
      <div style="background: #fff; position: relative; height: 100px; width: 100%; margin-top: -15px; border-radius: 5px">
        <div style="display: flex; height: 100%; justify-content: center; align-items: center">
          <div v-for="(item, index) in category" @click="gotoUrl(item)" style="margin: 0 10px" :key="index">
            <image style="width: 45px; height: 45px" :src="'http://www.wantongkonggu.cn/' + item.imageUrl"></image>
            <div style="margin-top: 5px; font-size: 12px">{{ item.categoryName }}</div>
          </div>
        </div>
      </div>
      <div style="display: flex; margin-top: 10px; justify-content: space-between">
        <image style="width: 50%; display: flex; align-items: center; height: 92px" @click="navigateToLeft" :src="leftImage"></image>
        <image style="margin-left: 5px; width: 50%; display: flex; align-items: center; height: 92px" @click="navigateToRight" :src="rightImage"></image>
      </div>
      <div>
        <image style="width: 100%; height: 120px; margin-top: 5px" :src="bottomImage2" @click="showInvitePopup"></image>
      </div>
      <div>
        <image style="width: 100%; height: 120px; margin-top: 5px" :src="bottomImage" @click="navigateToBottom"></image>
      </div>

      <!-- 无数据提示 -->
      <div v-if="showNoData" style="text-align: center; padding: 50px 0">
        <div style="font-size: 16px; color: #999; margin-bottom: 20px">附近社区暂无可用商户</div>
        <button @click="showInvitePopup" style="background-color: #ff581f; color: white; border: none; border-radius: 20px; font-size: 14px">邀请商户入驻</button>
      </div>

      <div v-else>
        <div style="display: flex">
          <div style="width: 50%; margin-right: 3px">
            <div @click="goActive(item)" v-for="item in tableData[0]" style="width: 100%; background-color: #fff; border-radius: 5px">
              <div class="dadwadad" style="padding: 5px; margin: 5px 0">
                <image mode="widthFix" style="width: 100%; border-radius: 5px; object-fit: cover" :src="'http://www.wantongkonggu.cn/' + item.icon"></image>
                <div style="display: flex; height: 35px; align-items: center">
                  <div style="color: #ff4000; font-weight: bold">￥{{ item.price }}</div>
                  <div style="border: 1px solid #ff4000; font-size: 12px; border-radius: 3px; padding: 1px 3px; background: #ffe7dd; color: #ff4000; margin-left: 10px">团购活动</div>
                </div>
                <div style="font-size: 14px">{{ item.name }}</div>
                <div style="font-size: 12px; margin-top: 5px; color: #3e3f43">{{ item.merName }}</div>
                <div v-if="item.distance" style="text-align: right; font-size: 12px; color: #999">{{ formatDistance(item.distance) }}</div>
              </div>
            </div>
          </div>
          <div style="width: 50%; margin-left: 3px">
            <div @click="goActive(item)" v-for="item in tableData[1]" style="width: 100%; background-color: #fff; border-radius: 5px">
              <div class="dadwadad" style="padding: 5px; margin: 5px 0">
                <image mode="widthFix" style="width: 100%; border-radius: 5px; object-fit: cover" :src="'http://www.wantongkonggu.cn/' + item.icon"></image>
                <div style="display: flex; height: 35px; align-items: center">
                  <div style="color: #ff4000; font-weight: bold">￥{{ item.price }}</div>
                  <div style="border: 1px solid #ff4000; font-size: 12px; border-radius: 3px; padding: 1px 3px; background: #ffe7dd; color: #ff4000; margin-left: 10px">团购活动</div>
                </div>
                <div style="font-size: 14px">{{ item.name }}</div>
                <div style="font-size: 12px; margin-top: 5px; color: #3e3f43">{{ item.merName }}</div>
                <div v-if="item.distance" style="text-align: right; font-size: 12px; color: #999">{{ formatDistance(item.distance) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 加载动画 -->
    <div v-if="loading" style="text-align: center; padding: 15px">
      <div>{{ loadingText }}</div>
    </div>

    <!-- 商户入驻弹窗 -->
    <uni-popup ref="invitePopup" type="center">
      <div style="background: white; border-radius: 10px; padding: 20px; text-align: center; width: 85vw; max-width: 400px">
        <div style="font-size: 18px; font-weight: bold; margin-bottom: 15px; color: #333">邀请商户入驻</div>
        <div style="position: relative; margin-bottom: 15px">
          <u-swiper
            :list="inviteQrCodeList"
            keyName="image"
            height="250"
            indicatorMode="dot"
            imgMode="aspectFit"
            bgColor="transparent"
            @click="handleSwiperClick"
            @change="handleSwiperChange"
            style="height: 250px"
          ></u-swiper>
        </div>
        <div style="margin: 15px 0; font-size: 15px; color: #666; min-height: 24px">{{ qrCodeDescription }}</div>
        <div style="display: flex; justify-content: center; margin: 15px 0; font-size: 13px; color: #999">
          <!--           <div style="margin: 0 8px; padding: 5px 10px; background-color: #f5f5f5; border-radius: 15px">长按图片保存</div>
          <div style="margin: 0 8px; padding: 5px 10px; background-color: #f5f5f5; border-radius: 15px">微信扫一扫</div> -->
        </div>
        <button @click="closeInvitePopup" style="margin-top: 10px; background-color: #ff581f; color: white; border: none; border-radius: 25px; font-size: 15px">关闭</button>
      </div>
    </uni-popup>
  </div>
</template>
<script>
import { ebMerActivityList, ebConfig, ebConfigList } from "../../utils/api/local";
import { merCategory } from "../../utils/api/api.js";
import { getUserInfo, programlogin } from "../../utils/request_api.js"; /* 登录界面挪动接口 */
import { notBindingPhone } from "../../utils/api/api.js";
import QQMapWX from "../../common/qqmap-wx-jssdk.js";
import uniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue";

export default {
  components: {
    uniPopup,
  },
  data() {
    return {
      tableData: [[], []],
      category: [],
      list1: [
        {
          img: "http://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/17/Property 1=001@2x_20251017093824A004.png",
          merId: "1736570444448021",
        },
        {
          img: "http://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/17/Property 1=003@2x_20251017093915A005.png",
          merId: "100",
        },
        {
          img: "http://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/17/Property 1=002@2x_20251017093929A006.png",
          merId: "1751873058997917",
        },
      ],
      bannerList: [],
      // 邀请商户入驻二维码轮播图数据
      inviteQrCodeList: [],
      defaultInviteQrCodeList: [
        {
          image: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/19/111223333_20251119161656A003.png",
          title: "请用微信扫二维码联系客服",
        },
        {
          image: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/19/666666_20251119171303A010.png",
          title: "店铺入驻资料收集表",
        },
      ],
      qrCodeDescription: "请用微信扫二维码联系客服",
      pageNum: 1,
      pageSize: 10,
      loading: false,
      loadingText: "加载中...",
      total: 0,
      searchName: "",
      yaoiqngID: "",
      locationName: "定位中...",
      longitude: "",
      latitude: "",
      qqmapsdk: null,
      showNoData: false, // 添加无数据状态变量
      // 默认图片URL
      defaultLeftImage: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/24/物业_20251124092339A037.png",
      defaultRightImage: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/24/物业_20251124092339A037.png",
      defaultBottomImage: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/24/消费返物业费_20251124101736A040.png",
      // 实际使用的图片URL和跳转链接
      leftImage: "",
      rightImage: "",
      bottomImage: "",
      leftJumpUrl: "",
      rightJumpUrl: "",
      bottomJumpUrl: "",
      leftJumpManner: "",
      rightJumpManner: "",
      bottomJumpManner: "",
      bottomJumpManner2: "",
      bottomJumpUrl2: "",
      bottomImage2: "",
      defaultBottomImage2: "",
    };
  },
  onLoad(options) {
    console.log("🚀 ~ options:", options);
    this.yaoiqngID = options.yaoiqngID;
    this.userType = options.type;
    // 初始化腾讯地图SDK
    this.qqmapsdk = new QQMapWX({
      key: "VKOBZ-UH563-QUB3I-ONVZB-WOYB6-SKFQ4", // 这里需要替换为实际的腾讯地图key
    });
    this.getebConfig();
    this.$nextTick(() => {
      this.initUser();
    });
  },
  mounted() {
    // 页面加载时获取地理位置并加载数据
    this.getCurrentLocation();
  },
  onPullDownRefresh() {
    // 下拉刷新
    this.pageNum = 1;
    this.tableData = [[], []];
    this.getData().finally(() => {
      uni.stopPullDownRefresh();
    });
  },
  onReachBottom() {
    // 上拉加载
    // 判断是否还有更多数据
    if (this.tableData[0].length + this.tableData[1].length < this.total) {
      this.pageNum++;
      this.getData();
    } else {
      this.loading = true;
      this.loadingText = "没有更多数据了";
      setTimeout(() => {
        this.loading = false;
      }, 1000);
    }
  },
  methods: {
    getebConfig() {
      ebConfig()
        .then((res) => {
          if (res.code == 200) {
            this.imgConfigID = res.rows[0].id;

            // 获取左侧图片配置 (res.rows[2].id)
            if (res.rows[2] && res.rows[2].id) {
              const leftConfigId = res.rows[2].id;
              ebConfigList({ ebHomepageConfigId: leftConfigId })
                .then((response) => {
                  if (response.code == 200 && response.rows && response.rows.length > 0) {
                    // 使用配置的第一项
                    const configItem = response.rows[0];
                    this.leftImage = configItem.imageUrl ? "http://www.wantongkonggu.cn/" + configItem.imageUrl : this.defaultLeftImage;
                    this.leftJumpUrl = configItem.jumpUrl || "";
                    this.leftJumpManner = configItem.jumpManner || "";
                  } else {
                    this.leftImage = this.defaultLeftImage;
                  }
                })
                .catch(() => {
                  this.leftImage = this.defaultLeftImage;
                });
            } else {
              this.leftImage = this.defaultLeftImage;
            }

            // 获取右侧图片配置 (res.rows[1].id)
            if (res.rows[1] && res.rows[1].id) {
              const rightConfigId = res.rows[1].id;
              ebConfigList({ ebHomepageConfigId: rightConfigId })
                .then((response) => {
                  if (response.code == 200 && response.rows && response.rows.length > 0) {
                    // 使用配置的第一项
                    const configItem = response.rows[0];
                    this.rightImage = configItem.imageUrl ? "http://www.wantongkonggu.cn/" + configItem.imageUrl : this.defaultRightImage;
                    this.rightJumpUrl = configItem.jumpUrl || "";
                    this.rightJumpManner = configItem.jumpManner || "";
                  } else {
                    this.rightImage = this.defaultRightImage;
                  }
                })
                .catch(() => {
                  this.rightImage = this.defaultRightImage;
                });
            } else {
              this.rightImage = this.defaultRightImage;
            }

            // 获取底部图片配置 (res.rows[3].id)
            if (res.rows[3] && res.rows[3].id) {
              const bottomConfigId = res.rows[3].id;
              ebConfigList({ ebHomepageConfigId: bottomConfigId })
                .then((response) => {
                  if (response.code == 200 && response.rows && response.rows.length > 0) {
                    // 使用配置的第一项
                    const configItem = response.rows[0];
                    this.bottomImage = configItem.imageUrl ? "http://www.wantongkonggu.cn/" + configItem.imageUrl : this.defaultBottomImage;
                    this.bottomJumpUrl = configItem.jumpUrl || "";
                    this.bottomJumpManner = configItem.jumpManner || "";
                  } else {
                    this.bottomImage = this.defaultBottomImage;
                  }
                })
                .catch(() => {
                  this.bottomImage = this.defaultBottomImage;
                });
            } else {
              this.bottomImage = this.defaultBottomImage;
            }
            // 获取底部图片配置 (res.rows[5].id)
            if (res.rows[5] && res.rows[5].id) {
              const bottomConfigId = res.rows[5].id;
              ebConfigList({ ebHomepageConfigId: bottomConfigId })
                .then((response) => {
                  if (response.code == 200 && response.rows && response.rows.length > 0) {
                    // 使用配置的第一项
                    const configItem = response.rows[0];
                    this.bottomImage2 = configItem.imageUrl ? "http://www.wantongkonggu.cn/" + configItem.imageUrl : this.defaultBottomImage2;
                  } else {
                    this.bottomImage = this.defaultBottomImage2;
                  }
                })
                .catch(() => {
                  this.bottomImage = this.defaultBottomImage;
                });
            } else {
              this.bottomImage = this.defaultBottomImage;
            }
            // 获取弹窗图片配置 (res.rows[4].id)
            if (res.rows[4] && res.rows[4].id) {
              const popupConfigId = res.rows[4].id;
              ebConfigList({ ebHomepageConfigId: popupConfigId })
                .then((response) => {
                  if (response.code == 200 && response.rows && response.rows.length > 0) {
                    // 使用配置的数据生成弹窗图片列表
                    this.inviteQrCodeList = response.rows.map((item) => ({
                      image: "http://www.wantongkonggu.cn/" + item.imageUrl,
                      title: item.writing || "请用微信扫二维码联系客服",
                    }));

                    // 设置默认描述文字为第一项的标题
                    if (this.inviteQrCodeList.length > 0) {
                      this.qrCodeDescription = this.inviteQrCodeList[0].writing;
                    }
                  } else {
                    // 使用默认配置
                    this.inviteQrCodeList = [...this.defaultInviteQrCodeList];
                  }
                })
                .catch(() => {
                  // 使用默认配置
                  this.inviteQrCodeList = [...this.defaultInviteQrCodeList];
                });
            } else {
              // 使用默认配置
              this.inviteQrCodeList = [...this.defaultInviteQrCodeList];
            }

            ebConfigList({ ebHomepageConfigId: this.imgConfigID })
              .then((response) => {
                if (response.code == 200) {
                  this.imgList = response.rows;
                  console.log("🚀 ~  this.imgList:", this.imgList);

                  // 如果有配置数据，则使用配置的轮播图
                  if (this.imgList && this.imgList.length > 0) {
                    this.bannerList = this.imgList.map((item) => ({
                      img: "http://www.wantongkonggu.cn/" + item.imageUrl,
                      url: item.jumpUrl,
                      jumpManner: item.jumpManner,
                      name: item.name,
                    }));
                  } else {
                    // 否则使用默认轮播图
                    this.bannerList = this.list1;
                  }
                } else {
                  // 如果获取配置列表失败，使用默认轮播图
                  this.bannerList = this.list1;
                }
              })
              .catch(() => {
                // 如果请求出错，使用默认轮播图
                this.bannerList = this.list1;
              });
          } else {
            // 如果获取配置失败，使用默认轮播图和默认左右图片
            this.bannerList = this.list1;
            this.leftImage = this.defaultLeftImage;
            this.rightImage = this.defaultRightImage;
            this.bottomImage = this.defaultBottomImage;
            this.inviteQrCodeList = [...this.defaultInviteQrCodeList];
          }
        })
        .catch(() => {
          // 如果请求出错，使用默认轮播图和默认左右图片
          this.bannerList = this.list1;
          this.leftImage = this.defaultLeftImage;
          this.rightImage = this.defaultRightImage;
          this.bottomImage = this.defaultBottomImage;
          this.inviteQrCodeList = [...this.defaultInviteQrCodeList];
        });
    },
    initUser() {
      uni.showLoading();
      getUserInfo()
        .then((res) => {
          if (res.code === 401) {
            this.showloginJs();
          } else {
            this.userInfo = res.data;
            uni.setStorageSync("userInfo", res.data);
            uni.hideLoading();
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
          uni.hideLoading();
        });
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.code) {
            that.autoLogin(res.code);
          } else {
            uni.hideLoading();
            console.error("登录失败:", res.errMsg);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录失败:", err);
          uni.showToast({
            title: "微信登录失败，请稍后再试",
            icon: "none",
          });
        },
      });
    },
    /* 免登录-每个界面调用 */
    async autoLogin(code) {
      let that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            that.authKey = data.key;
            that.openIdadw = data.openId;
            if (data.type === "login") {
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.initUser();
              uni.hideLoading();
            } else {
              that.initUserregister();
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
          });
        },
      });
    },
    initUserregister() {
      var params = {
        key: this.authKey,
        type: "routine",
        openId: this.openIdadw,
        phone: "",
        password: "",
        captcha: "",
        codeOrPassword: "3",
        inviterLinkId: this.yaoiqngID ? this.yaoiqngID : "",
        inviteeType: this.userType,
      };
      notBindingPhone(params).then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          const data = res.data;
          uni.setStorageSync("uid", data.uid);
          uni.setStorageSync("token", data.token);
          uni.setStorageSync("userInfo_data", data);
          uni.setStorageSync("openID", this.authKey);
          this.initUser();
        }
      });
    },
    goActive(item) {
      uni.navigateTo({
        url: "/pages_h5/index/components/detail?id=" + item.ebMerId,
      });
      /*  uni.navigateTo({
        url:
          "/pages_h5/local_life/detailIndex?id=" +
          item.id +
          "&businessId=" +
          item.ebMerId +
          "&isLaundry=" +
          item.isLaundry +
          "&userType=" +
          +"&yaoiqngID=" +
          +"&isWatercard=" +
          item.isWatercard,
      }); */
    },
    /* 轮播图点击 */
    imgclick(index) {
      uni.navigateTo({
        url: "/pages_h5/myCenter/components/addCoupon",
      });
      return;
      const clickedItem = this.bannerList[index];

      // 如果有跳转链接和跳转方式
      if (clickedItem.url && clickedItem.jumpManner) {
        // 根据jumpManner判断跳转方式
        if (clickedItem.jumpManner == "nav") {
          // uni.开头的为uni跳转方式
          uni.navigateTo({
            url: clickedItem.url,
          });
        } else {
          // 其他情况默认使用redirectTo
          uni.switchTab({
            url: clickedItem.url,
          });
        }
      } else if (clickedItem.merId) {
        // 兼容默认轮播图的跳转方式
        uni.navigateTo({
          url: "/pages_h5/index/components/detail?id=" + clickedItem.merId,
        });
      }
    },
    gotoUrl(item) {
      if (item.categoryName == "大牌点餐") {
        uni.navigateTo({
          url: "/myPackage/pages/tiaozhuan/index",
        });
      } else {
        uni.navigateTo({
          url: item.jumpUrl,
        });
      }
    },
    navigateToBottom() {
      // 如果有配置跳转链接和跳转方式
      if (this.bottomJumpUrl && this.bottomJumpManner) {
        // 根据jumpManner判断跳转方式
        if (this.bottomJumpManner == "nav") {
          // nav表示使用navigateTo跳转
          uni.navigateTo({
            url: this.bottomJumpUrl,
          });
        } else {
          // 其他情况默认使用switchTab跳转
          uni.switchTab({
            url: this.bottomJumpUrl,
          });
        }
      } else {
        // 默认不跳转或可以添加默认跳转链接
        console.log("底部图片未配置跳转链接");
      }
    },
    navigateToRight() {
      // 如果有配置跳转链接和跳转方式
      if (this.rightJumpUrl && this.rightJumpManner) {
        // 根据jumpManner判断跳转方式
        if (this.rightJumpManner == "nav") {
          // nav表示使用navigateTo跳转
          uni.navigateTo({
            url: this.rightJumpUrl,
          });
        } else {
          // 其他情况默认使用switchTab跳转
          uni.switchTab({
            url: this.rightJumpUrl,
          });
        }
      } else {
        // 默认跳转
        uni.switchTab({
          url: "/pages_h5/wy/index",
        });
      }
    },
    navigateToLeft() {
      // 如果有配置跳转链接和跳转方式
      if (this.leftJumpUrl && this.leftJumpManner) {
        // 根据jumpManner判断跳转方式
        if (this.leftJumpManner == "nav") {
          // nav表示使用navigateTo跳转
          uni.navigateTo({
            url: this.leftJumpUrl,
          });
        } else {
          // 其他情况默认使用switchTab跳转
          uni.switchTab({
            url: this.leftJumpUrl,
          });
        }
      } else {
        // 默认跳转
        uni.navigateTo({
          url: "/pages_h5/householdServices/index",
        });
      }
    },
    handleSearch() {
      // 搜索功能，重置页码并重新加载数据
      this.pageNum = 1;
      this.tableData = [[], []];
      this.getData();
    },
    clearSearch() {
      // 清空搜索内容并重新加载数据
      this.searchName = "";
      this.pageNum = 1;
      this.tableData = [[], []];
      this.getData();
    },
    getCurrentLocation() {
      // 获取当前定位
      uni.getLocation({
        type: "gcj02",
        success: (res) => {
          this.longitude = res.longitude;
          this.latitude = res.latitude;
          // 通过逆地理编码获取具体地址名称
          this.getAddressFromCoordinates(res.longitude, res.latitude);
        },
        fail: (err) => {
          console.log("获取位置失败", err);
          // 检查用户是否拒绝了授权
          uni.getSetting({
            success: (res) => {
              if (res.authSetting["scope.userLocation"] === false) {
                // 用户已拒绝授权，引导用户重新授权
                uni.showModal({
                  title: "授权位置信息",
                  content: "需要获取您的位置信息来提供更精准的服务，请在设置中开启位置权限",
                  confirmText: "去设置",
                  cancelText: "取消",
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      // 引导用户去设置页面开启权限
                      uni.openSetting({
                        success: (settingRes) => {
                          if (settingRes.authSetting["scope.userLocation"]) {
                            // 用户开启了权限，重新获取位置
                            this.getCurrentLocation();
                          } else {
                            // 用户仍然未开启权限，使用默认位置
                            this.setDefaultLocation();
                          }
                        },
                        fail: () => {
                          this.setDefaultLocation();
                        },
                      });
                    } else {
                      // 用户取消授权，使用默认位置
                      this.setDefaultLocation();
                    }
                  },
                });
              } else {
                // 其他错误情况，使用默认位置
                this.setDefaultLocation();
              }
            },
            fail: () => {
              // 获取设置失败，使用默认位置
              this.setDefaultLocation();
            },
          });
        },
      });
    },
    setDefaultLocation() {
      // 设置默认位置
      this.locationName = "请选择位置";
      // 加载数据
      this.getData();
    },
    getAddressFromCoordinates(longitude, latitude) {
      // 使用腾讯地图API根据经纬度获取地址信息
      this.qqmapsdk.reverseGeocoder({
        location: {
          latitude: latitude,
          longitude: longitude,
        },
        success: (res) => {
          // 只展示具体的地域信息，而非完整省市区信息
          if (res.result.address_component) {
            // 优先使用具体的地区名称，如街道、地标等
            this.locationName =
              res.result.address_reference?.landmark_l2?.title ||
              res.result.address_reference?.landmark_l1?.title ||
              res.result.address_component.street ||
              res.result.address_component.district ||
              res.result.formatted_addresses.recommend ||
              res.result.address;
          } else {
            this.locationName = res.result.formatted_addresses.recommend || res.result.address;
          }

          // 如果还是获取不到合适的地址或地址太长，则简化处理
          if (!this.locationName || (this.locationName.includes("省") && this.locationName.length > 10)) {
            // 尝试去掉省份信息，只保留市区及以下的信息
            const recommend = res.result.formatted_addresses.recommend;
            if (recommend) {
              this.locationName = recommend.replace(/^.+?[市省]/, "");
            } else {
              this.locationName = res.result.address ? res.result.address.replace(/^.+?[市省]/, "") : "请选择位置";
            }
          }

          // 确保显示的位置信息不会太长，但不需要截断字符串，因为CSS会处理省略号显示
          if (this.locationName && this.locationName.length > 15) {
            // 对于特别长的位置名称，做一些合理的简化处理
            const parts = this.locationName.split(/[,，]/);
            if (parts.length > 1) {
              this.locationName = parts[0]; // 取第一个部分作为位置名
            }
          }

          // 获取位置名称后加载数据
          this.getData();
        },
        fail: (err) => {
          console.log("逆地理编码失败", err);
          // 如果逆地理编码失败，设置默认位置
          this.locationName = "请选择位置";
          // 加载数据
          this.getData();
        },
      });
    },
    chooseLocation() {
      // 选择位置
      uni.chooseLocation({
        success: (res) => {
          this.locationName = res.name || res.address;
          this.longitude = res.longitude;
          this.latitude = res.latitude;

          // 确保显示的位置信息不会太长，但不需要截断字符串，因为CSS会处理省略号显示
          if (this.locationName && this.locationName.length > 15) {
            // 对于特别长的位置名称，做一些合理的简化处理
            const parts = this.locationName.split(/[,，]/);
            if (parts.length > 1) {
              this.locationName = parts[0]; // 取第一个部分作为位置名
            }
          }

          // 重新加载数据以更新距离信息
          this.pageNum = 1;
          this.tableData = [[], []];
          this.getData();
        },
        fail: (err) => {
          console.log("选择位置失败", err);
          // 检查是否因为用户拒绝授权导致失败
          if (err.errMsg && err.errMsg.includes("fail auth deny")) {
            uni.showModal({
              title: "授权位置信息",
              content: "需要获取您的位置信息来提供更精准的服务，请在设置中开启位置权限",
              confirmText: "去设置",
              cancelText: "取消",
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting["scope.userLocation"]) {
                        // 用户开启了权限，重新调用选择位置
                        this.chooseLocation();
                      }
                    },
                  });
                }
              },
            });
          }
        },
      });
    },
    formatDistance(distance) {
      // 将米转换为千米
      // 确保distance是数字类型
      const dist = parseFloat(distance);

      // 检查是否为有效数字
      if (isNaN(dist)) {
        return "距离未知";
      }

      if (dist < 1000) {
        return dist.toFixed(0) + "m";
      } else {
        return (dist / 1000).toFixed(2) + "km";
      }
    },
    getData() {
      // 显示加载动画
      if (this.pageNum === 1) {
        this.loading = true;
        this.loadingText = "加载中...";
        // 重置无数据状态
        this.showNoData = false;
      } else {
        this.loading = true;
        this.loadingText = "正在加载更多...";
      }

      // 准备请求参数
      const params = {
        isDefMerActive: 0,
        status: 0,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        name: this.searchName,
      };

      // 如果有经纬度信息，则添加到参数中
      if (this.longitude && this.latitude) {
        params.lng = this.longitude;
        params.lat = this.latitude;
      }

      return Promise.all([merCategory(), ebMerActivityList(params)])
        .then(([categoryRes, activityRes]) => {
          // 处理分类数据
          if (this.pageNum === 1) {
            this.category = categoryRes.data
              .slice(0, 5)
              .filter((item) => item.categoryName !== "线上商城") // 过滤掉 categoryName 为 '线上商城' 的项
              .map((item) => {
                return {
                  ...item,
                  jumpUrl: "/pages_h5/index/merList?categoryId=" + item.merchantCategoryId,
                };
              });
          }

          // 处理活动数据
          const data = activityRes.rows;
          this.total = activityRes.total;

          if (data.length === 0 && this.pageNum === 1) {
            // 第一页就没有数据，显示无数据提示
            this.showNoData = true;
          } else {
            this.showNoData = false;
            data.forEach((item, index) => {
              if (index % 2 == 0) {
                this.tableData[0].push(item);
              } else {
                this.tableData[1].push(item);
              }
            });
          }
        })
        .catch((error) => {
          console.error("数据加载失败:", error);
          this.loadingText = "加载失败";
        })
        .finally(() => {
          // 隐藏加载动画
          setTimeout(() => {
            this.loading = false;
          }, 500);
        });
    },
    // 显示邀请入驻弹窗
    showInvitePopup() {
      this.$refs.invitePopup.open();
    },
    // 关闭邀请入驻弹窗
    closeInvitePopup() {
      this.$refs.invitePopup.close();
    },
    // 轮播图切换事件
    handleSwiperChange(index) {
      console.log("🚀 ~ index:", index);
      this.qrCodeDescription = this.inviteQrCodeList[index.current].title;
    },
    // 轮播图点击事件
    handleSwiperClick(index) {
      // 点击时也可以显示当前图片的描述
      this.qrCodeDescription = this.inviteQrCodeList[index].title;
    },
  },
};
</script>

<style>
page {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
}
.dadwadad {
  width: calc(100% - 10px);
}
.bendishengh {
  height: 100px;
  background-image: url("http://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/17/Group 330@3x_20251017085538A001.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
/* .wuyefuw {
  height: 92px;
  background-image: url("https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/11/24/物业_20251124092339A037.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
} */
</style>
